package com.kaigejava.utils;

import java.io.*;
import java.util.zip.*;

/**
 * @author kaigejava
 * zip操作的工具类
 */
public class ZipUtil {
    /**
     * 使用zip进行压缩
     *
     * @param str 压缩前的文本
     * @return 返回压缩后的文本
     */
    public static final String zip(String str) {
        if (str == null){
            return null;
        }
        byte[] compressed;
        ByteArrayOutputStream out = null;
        ZipOutputStream zout = null;
        String compressedStr = null;
        try {
            out = new ByteArrayOutputStream();
            zout = new ZipOutputStream(out);
            zout.putNextEntry(new ZipEntry("0"));
            zout.write(str.getBytes());
            zout.closeEntry();
            compressed = out.toByteArray();
            compressedStr = new sun.misc.BASE64Encoder().encodeBuffer(compressed);
        } catch (IOException e) {
            compressed = null;
        } finally {
            if (zout != null) {
                try {
                    zout.close();
                } catch (IOException e) {
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                }
            }
        }
        return compressedStr;
    }


    /**
     * 使用zip进行解压缩
     *
     * @param compressedStr 压缩后的文本
     * @return 解压后的字符串
     */
    public static final String unzip(String compressedStr) {
        if (compressedStr == null) {
            return null;
        }


        ByteArrayOutputStream out = null;
        ByteArrayInputStream in = null;
        ZipInputStream zin = null;
        String decompressed = null;
        try {
            byte[] compressed = new sun.misc.BASE64Decoder().decodeBuffer(compressedStr);
            out = new ByteArrayOutputStream();
            in = new ByteArrayInputStream(compressed);
            zin = new ZipInputStream(in);
            zin.getNextEntry();
            byte[] buffer = new byte[1024];
            int offset = -1;
            while ((offset = zin.read(buffer)) != -1) {
                out.write(buffer, 0, offset);
            }
            decompressed = out.toString();
        } catch (IOException e) {
            decompressed = null;
        } finally {
            if (zin != null) {
                try {
                    zin.close();
                } catch (IOException e) {
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                }
            }
        }
        return decompressed;
    }


    /**
     * 从ZIP中读取文件
     * @param fileName      文件名称.如：c:/a/a.zip
     * @param endWith       需要读取等候后缀。如txt
     * @return
     * @throws IOException
     */
    public static String readZip(String fileName,String endWith) throws IOException{
        ZipFile zip = new ZipFile(fileName);
        File file = new File(fileName);
        String parentZipParent = file.getParent(); //获取上级文件夹解压到这里
        File temp = file;
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fileName));
        ZipInputStream zis = new ZipInputStream(bis);
        ZipEntry entry ;//用于获取压缩文件中的文件或文件夹
        StringBuffer sb = new StringBuffer();
        while((entry = zis.getNextEntry())!=null){
            if(entry.isDirectory()){
                System.out.println("文件夹");
            }else{
             //   System.out.println("file:"+entry.getName());
                if(entry.getName().endsWith(endWith)){
                    BufferedReader reader = new BufferedReader(new InputStreamReader(zip.getInputStream(entry)));
                    String line = null;
                    while((line = reader.readLine())!=null){
                       // System.out.println(line);
                        sb.append(line);
                    }
                } else if (entry.getName().endsWith("zip")){  //判断是否为压缩包，若是则将其解压出再读取
                    temp = new File(parentZipParent + "\\" + entry.getName());
                  //  System.out.println(temp.getAbsolutePath());
                    if (!temp.getParentFile().exists()) {
                        temp.getParentFile().mkdirs();
                    }
                    OutputStream os = new FileOutputStream(temp);
                    ////通过ZipFile的getInputStream方法拿到具体的ZipEntry的输入流
                    InputStream is = zip.getInputStream(entry);
                    int len = 0;
                    while ((len = is.read()) !=-1) {
                        os.write(len);
                    }
                    sb.append(readZip(temp.getAbsolutePath(),endWith));
                }
            }
        }
        //System.out.println("sb:"+sb.toString());
        return sb.toString();
    }


}

